Page({
  data: {
    id: '',
    title: '',
    content: '',
    selectedTag: ''
  },

  onLoad(options) {
    if (options.id) {
      this.loadNote(options.id);
    }
  },

  loadNote(id) {
    const notes = wx.getStorageSync('notes') || [];
    const note = notes.find(n => n.id === id);
    if (note) {
      this.setData({
        id: note.id,
        title: note.title,
        content: note.content,
        selectedTag: note.tag || ''
      });
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 标签选择
  selectTag(e) {
    const tag = e.currentTarget.dataset.tag;
    this.setData({
      selectedTag: this.data.selectedTag === tag ? '' : tag
    });
  },

  onTitleInput(e) {
    this.setData({ title: e.detail.value });
  },

  onContentInput(e) {
    this.setData({ content: e.detail.value });
  },

  saveNote() {
    const { id, title, content, selectedTag } = this.data;
    
    if (!content.trim()) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      });
      return;
    }

    let notes = wx.getStorageSync('notes') || [];
    
    if (id) {
      // 编辑现有笔记
      const index = notes.findIndex(n => n.id === id);
      if (index !== -1) {
        notes[index] = {
          ...notes[index],
          title: title || '无标题',
          content,
          tag: selectedTag,
          time: this.formatTime(new Date())
        };
      }
    } else {
      // 新建笔记
      const newNote = {
        id: Date.now().toString(),
        title: title || '无标题',
        content,
        tag: selectedTag,
        time: this.formatTime(new Date())
      };
      notes.unshift(newNote);
    }

    wx.setStorageSync('notes', notes);
    
    wx.showToast({
      title: '保存成功',
      icon: 'success'
    });

    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
  },

  deleteNote() {
    const { id } = this.data;
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条笔记吗？',
      success: (res) => {
        if (res.confirm) {
          let notes = wx.getStorageSync('notes') || [];
          notes = notes.filter(n => n.id !== id);
          wx.setStorageSync('notes', notes);
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });

          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      }
    });
  },

  formatTime(date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    
    return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
  }
});